/**
 * Created by XianTao on 2016/11/12
 * <p/>
 * Copyright (c) 2015-2015
 * Apache License
 * Version 2.0, January 2004
 * http://www.apache.org/licenses/
 */
package org.lego.wechat.base.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.lego.jpa.base.entity.UUIDEntity;
import org.lego.util.StringUtil;

import javax.persistence.*;
import java.util.List;

@Entity
@Table
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
public class WxMenu extends UUIDEntity {
    public static final int MAX_MENU_NUMBER = 3;
    public static final int MAX_SUB_MENU_NUMBER = 5;

    public static final int VIEW_TYPE_NORMAL = 1;
    public static final int VIEW_TYPE_SNSAPI_BASE = 2;
    public static final int VIEW_TYPE_SNSAPI_USERINFO = 3;

    private String name;
    private String type;    // view, click, complex
    private String content;
    private Integer viewType;    // 如果type是view，那么可以设置此值为：1:普通链接；2:snsapi_base网页授权；3:snsapi_userinfo网页授权
    private Integer sort;
    @ManyToOne
    @JoinColumn(name = "parent_id")
    private WxMenu parent;
    @OneToMany(mappedBy = "parent")
    private List<WxMenu> children;

    public String getUrlByViewType(String corpId) {
        if (VIEW_TYPE_SNSAPI_BASE == this.getViewType()) {
            return getAuthorizeUrl(corpId, this.getContent(), "snsapi_base", "");
        } else if (VIEW_TYPE_SNSAPI_USERINFO == this.getViewType()) {
            return getAuthorizeUrl(corpId, this.getContent(), "snsapi_userinfo", "");
        } else {
            return this.getContent();
        }
    }

    private String getAuthorizeUrl(String corpId, String url, String scope, String state) {
        String urlFormat = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect";
        return String.format(urlFormat, corpId, StringUtil.encode(url), scope, state);
    }
}
